package com.hsq.spzx.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.hsq.spzx.model.entity.product.Category;
import com.hsq.spzx.product.mapper.product.CategoryMapper;
import com.hsq.spzx.product.service.CategoryService;
import com.hsq.spzx.product.utils.MenuHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;


import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author hsq
 * @date 2025-06-13 下午5:00
 */
@Slf4j
@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public List<Category> findOneCategory() {
        // 从Redis缓存中查询所有的一级分类数据
        String categoryListOne = redisTemplate.opsForValue().get("category:one");
        if (StringUtils.hasText(categoryListOne)) {
            log.info("从Redis缓存中查询到了所有的一级分类数据");
            return JSON.parseArray(categoryListOne, Category.class);
        }
        List<Category> categoryList = categoryMapper.findOneCategory();
        log.info("从数据库中查询到了所有的一级分类数据{}", categoryList);
        redisTemplate.opsForValue().set("category:one",
                                        JSON.toJSONString(categoryList),
                                        7, TimeUnit.DAYS);
        return categoryList;
    }

    @Cacheable(value = "category", key = "'all_tree'")
    @Override
    public List<Category> findCategoryTree() {
        List<Category> allCategoryList = categoryMapper.findAll();
//        List<Category> oneCategoryList = MenuHelper.buildTree(allCategoryList);
        List<Category> oneCategoryList = MenuHelper.buildTree1(allCategoryList);
        return oneCategoryList;
    }
}
